from Accounting.Fee.FeeBase import Fee
from DataAccess.DBConnFactory import DBConnFactory
from string import Template


class FailoverFee(Fee):
	def __init__(self, fee_obj):
		Fee.__init__(self, fee_obj.reference_date(), fee_obj.currency(), 
					fee_obj.is_payment_date, fee_obj.is_redem, fee_obj.entity)
		self.fee_obj = fee_obj		
		self.is_official = 'UNKNOWN'
		
	def category(self):
		return self.fee_obj.category()
		
	def type(self):
		return self.fee_obj.type()
		
	def impl_check_official_existence(self, entity):
		if self.is_official != 'UNKNOWN':
			return self.is_official
		
		cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
		sql_tpl = Template('''select amount from fee 
							where ref_date=TO_DATE('${DATE}','yyyy-mm-dd') 
								and entity='${ENTITY}' 
								and subtype='${TP}'
								and official='T' ''')
		cursor.execute(sql_tpl.substitute(DATE=self.ref_date.isoformat(), 
										ENTITY=entity.get_entity_id(), 
										TP=self.fee_obj.type()))
		r = cursor.fetchone()
		if r and len(r)>0:
			self.amt = r[0]
			self.fee_obj.amt = self.amt
			self.is_official = True
		else:
			self.is_official = False
		
		return self.is_official
		
		
	def calculate(self):
		if not self.impl_check_official_existence(self.entity):
			self.fee_obj.calculate()
			self.amt = self.fee_obj.amount()
		
	def persistence(self):
		if not self.impl_check_official_existence(self.entity):
			return self.fee_obj.persistence()
			
	#def pay_amount(self):
	#	if not self.impl_check_official_existence(self.entity):	
	#		return self.fee_obj.pay_amount()
	#	else:
	#		if self.fee_obj.is_payment_date:
	#			return self.amt
	#		else:
	#			return 0
	
	def is_pay_date(self):
		return self.fee_obj.is_pay_date()
	
		
	def cash_redeming(self): 
		return self.fee_obj.cash_redeming()
		
	def trigger_fund_share_chg(self, ref_date):	
		return self.fee_obj.trigger_fund_share_chg(ref_date)
		
		